const { stringifyRequest } = require("loader-utils");
const selectLoader = require.resolve("./Select.js");
const { scriptReg, styleReg, langReg, removeTagReg } = require('./utils');

function obtainAttr(code) {
  return {
    lang: langReg.exec(code)[1],
  };
}

module.exports = function (source) {
  const scriptCode = scriptReg.exec(source)[0];
  const scriptAttr = obtainAttr(scriptCode);

  const styleCode = styleReg.exec(source)[0];
  const styleAttr = obtainAttr(styleCode);

  // 这里需要注意相对路径和!=!双匹配语法
  const styleRequest = stringifyRequest(
    this,
    `${this.resourcePath}.style.${styleAttr.lang}!=!${selectLoader}!${this.resourcePath}?type=style`
  );

  const scriptRequest = stringifyRequest(
    this,
    `${this.resourcePath}.script.${scriptAttr.lang}!=!${selectLoader}!${this.resourcePath}?type=script`
  );

  const htmlRequest = stringifyRequest(
    this,
    `${this.resourcePath}.script.js!=!${selectLoader}!${this.resourcePath}?type=html`
  );


  return `
  import ${styleRequest};
  import _script from ${scriptRequest};
  import _createNode from ${htmlRequest};
  
  _script.prototype._createNode = _createNode

  export default _script;
  `;
};
